import storage from './storage';
class Mysocket {
    websocket = null;
    /**建立连接 */
    public  createSocket() {
        console.log(this.websocket);
        if (!this.websocket) {
            let url=storage.getSessionStorage("websockUrl");
            this.websocket = new WebSocket(url);
            console.log('建立websocket连接')
            console.log(this);
            console.log(this.websocket);
            //连接后发送参数
            this.websocket.onopen = ()=>{
                console.log(this.websocket);
                let sendMsg={'apiToken':storage.getSessionStorage('LoginForm')['token'],'eventType':'webConnect'};
                this.websocket.send(JSON.stringify(sendMsg));
            };
            this.websocket.onmessage = this.onmessageWS;
            this.websocket.onerror = this.onerrorWS;
            this.websocket.onclose = this.oncloseWS;
        } else {
          console.log('websocket已连接');
        }
    }
    /**连接失败重连 */
    public onerrorWS() {
        if(this.websocket){
            this.websocket.close();
            this.websocket=null;
            this.createSocket(); //重连
        }
    }
    /**WS数据接收统一处理 */
    public onmessageWS(e) {
        window.dispatchEvent(new CustomEvent('onmessageWS', {
            detail: {
                data: e
            }
      }))
    }
    /**关闭WS */
    public oncloseWS() {
        console.log(this.websocket);
        if(this.websocket){
            console.log(this.websocket);
            this.websocket.close();
            console.log('websocket已断开');
            this.websocket=null;
        }else {
            console.log('websocket没连接');
        }
    }
}
export default new Mysocket();
